#include "MyString.h"
#include "DynamicArray.h"
#include <string.h>
#include<stdio.h>
#include <stdlib.h>

void Print(MyString *obj);
int IsEqual(MyString *obj1,MyString *obj2);
int IsContains(MyString *dest,MyString *src);
int Size(MyString *obj);
void RemoveString(MyString*dest,const char *str);
void InsertString(MyString*dest,const char *str, int index);

void Initialize(MyString *obj, const char *str)//初始化
{    obj->size=strlen(str);

//new note
       obj->string=(char *)malloc(sizeof(char )*(obj->size+1));
      if(obj->string == NULL)
      {
         printf("MyString malloc error!\n");
        return ;
      }
    strcpy(obj->string,str);
    
    obj->IsContains=IsContains;
    obj->insertString=InsertString;
    obj->isEqual=IsEqual;
    obj->print=Print;
    obj->removeString=RemoveString;
    obj->StringSize=Size;
}

void FreeMyString(MyString *obj)
{
    if(obj->string!=NULL)
    {
        free(obj->string);
        obj->string=NULL;
    }
}

int IsEqual(MyString *obj1, MyString *obj2)
{
    if(strcmp(obj1->string,obj2->string)==0)
    {
        return 1;
    }
    else 
    {
        return 0;
    }
}

int IsContains(MyString *obj, MyString *src)
{
    char *str =strstr(obj->string,src->string);
    if(str ==NULL)
     {
        return 0;
     }
     else 
     {
        return 1;
     }
    return 0;
}

int Size(MyString *obj)
{
    return obj->size;
}

void RemoveString(MyString *obj, const char *str)
{
  char *RMstr=strstr(obj->string,str);
  if(RMstr == NULL)
  {
    return;
  }
  else 
  {
    char *destination=RMstr + strlen(str);
    while(*destination!='\0')
    {
        *RMstr=*destination;
        RMstr++;
        destination++;
    }
    *RMstr='\0';
  }
}

void InsertString(MyString *obj, const char *str, int index)
{
   if(index < 0 || index > obj->size)
 {
    return;
 } 
 int  new_str_len = obj->size+strlen(str)+1;
 char *new_str = (char*)malloc(new_str_len);
 if(new_str == NULL)
 {
    printf("insertstring malloc error!\n");
    return ;
 }

 strncpy(new_str,obj->string,index);
 strncpy(new_str+index,str,strlen(str));
 strcpy(new_str+index+strlen(str),obj->string+index);

 free(obj->string);
 obj->string = new_str;
 obj->size = strlen(obj->string);
}

void Print(MyString *obj)
{
    printf("%s\n",obj->string);
}

